import os
import sys

def check_video_directory():
    """检查视频目录状态"""
    video_dir = "videos"
    print(f"🔍 检查视频目录: {video_dir}")
    
    # 检查目录是否存在
    if not os.path.exists(video_dir):
        print(f"❌ 目录不存在，创建目录...")
        try:
            os.makedirs(video_dir)
            print(f"✅ 目录创建成功")
        except Exception as e:
            print(f"❌ 目录创建失败: {e}")
            return False
    
    # 检查目录权限
    test_file = os.path.join(video_dir, "test_write.txt")
    try:
        with open(test_file, 'w') as f:
            f.write("test")
        os.remove(test_file)
        print(f"✅ 目录可写")
    except Exception as e:
        print(f"❌ 目录不可写: {e}")
        return False
    
    # 列出目录内容
    files = os.listdir(video_dir)
    print(f"📁 目录内容: {files}")
    
    return True

def check_moviepy_installation():
    """检查MoviePy安装"""
    print(f"\n🔍 检查MoviePy安装...")
    try:
        from moviepy.editor import VideoFileClip, TextClip, ColorClip
        print(f"✅ MoviePy导入成功")
        return True
    except Exception as e:
        print(f"❌ MoviePy导入失败: {e}")
        return False

def test_video_creation():
    """测试视频创建"""
    print(f"\n🎬 测试视频创建...")
    try:
        from moviepy.editor import ColorClip, TextClip, CompositeVideoClip
        
        # 创建简单的测试视频
        output_path = "videos/test_video.mp4"
        
        background = ColorClip(size=(640, 480), color=(255, 0, 0), duration=2)
        text_clip = TextClip("测试视频", fontsize=30, color='white')
        text_clip = text_clip.set_position('center').set_duration(2)
        
        video = CompositeVideoClip([background, text_clip])
        video.write_videofile(output_path, fps=24, verbose=False, logger=None)
        
        # 检查文件是否创建
        if os.path.exists(output_path):
            file_size = os.path.getsize(output_path)
            print(f"✅ 测试视频创建成功! 大小: {file_size} 字节")
            os.remove(output_path)  # 清理测试文件
            return True
        else:
            print(f"❌ 测试视频文件未创建")
            return False
            
    except Exception as e:
        print(f"❌ 测试视频创建失败: {e}")
        import traceback
        print(traceback.format_exc())
        return False

if __name__ == "__main__":
    print("🚀 开始检查视频生成环境...")
    
    success = True
    success &= check_video_directory()
    success &= check_moviepy_installation()
    success &= test_video_creation()
    
    if success:
        print("\n🎉 所有检查通过！视频生成环境正常。")
    else:
        print("\n❌ 部分检查失败，请查看上面的错误信息。")